const { app } = require("electron");
const Store = require("electron-store");
const sqlite3 = require("sqlite3");
let option = {
    name: "config", //文件名称,默认 config
    fileExtension: "json", //文件后缀,默认json
    cwd: app.getPath("userData"), //文件位置,尽量不要动
    //    encryptionKey:"aes-256-cbc" ,//对配置文件进行加密
    clearInvalidConfig: true, // 发生 SyntaxError  则清空配置,
};

const store = new Store(option);
console.log(option.cwd);
const db = new sqlite3.Database(`${option.cwd}/sqlite.db`);

const cmd = {
    sqliteInitTable: function (arg) {
        return new Promise((resolve, reject) => {
            db.all(
                `select * from sqlite_master where type='table' and name='${arg["table"]}';`,
                (err, res) => {
                    if (res.length > 0) {
                        resolve(res);
                    } else {
                        db.run(arg["sql"]);
                    }
                }
            );
        });
    },
    sqlliteExecute: function (arg) {
        let st = db.prepare(arg["sql"]);
        st.run();
        st.finalize();
    },
    sqliteGetAll: function (arg) {
        return new Promise((resolve, reject) => {
            db.all(arg["sql"], (err, res) => {
                resolve(res);
            });
        });
    },
    sqliteGetByLabel: function (arg) {
        return new Promise((resolve, reject) => {
            db.get(arg["sql"], arg["text"], (err, row) => {
                resolve(row);
            });
        });
    },
    sqliteInsert: function (arg) {
        let st = db.prepare(arg["sql"]);
        st.run(arg["param"]);
        st.finalize();
    },
    sqliteEach: function (arg) {
        return new Promise((resolve, reject) => {
            db.each(arg["sql"], (err, res) => {
                resolve(res);
            });
        });
    },
    init: function (arg) {
        let data = {};
        if (!store.get(arg["db"])) {
            store.set(arg["db"], data);
        }
    },
    set: function (data) {
        this.init(data);
        store.set(data["key"], data["value"]);
        return { msg: "添加成功" };
    },
    getAll: function (data) {
        this.init(data);
        return { data: store.get(data["db"]) };
    },
    delete: function (data) {
        store.delete(data["key"]);
    },
    update: function (data) {
        store.update(data["key"], data["value"]);
    },
    show: function (data) {
        if (data["url"]) {
            data["window"].loadFile(data["url"]);
        }
        data["window"].show();
    },
};

exports.cmd = cmd;
